import React from "react";
import Button from '@iso/components/uielements/button';
import {UploadOutlined} from "@ant-design/icons";
import {showErrorMessage} from "@iso/containers/Feedback/Message/MessageUtils";


export default  class FormDataFileUploadButton extends React.Component {

    state = {

    };

    contains=(val,array)=> {
        for (let i = 0; i < array.length; i++) {
            if (array[i].toLowerCase() == val.toLowerCase()) {
                return true;
            }
        }
        return false;
    };



    render() {

        let buttonId=this.props.config.id;

        let title=this.props.config.title!=undefined?this.props.config.title:"上传";

        let className=this.props.config.className!=undefined?this.props.config.className:"course-upload";

        return (

            <div className={className}>
                <Button
                    key="submit"
                    type="primary"
                    icon={<UploadOutlined/>}
                    size='middle'
                    disabled={this.props.disabled}
                    onClick={() =>{
                        document.getElementById(buttonId).click();
                    }}>
                    {title}
                </Button>

                <input type={"file"} multiple id={buttonId} name={"input-file-upload"} style={{display: "none"}} onChange={(e)=>{
                    let files=e.target.files;
                    let accept= this.props.config.accept;
                    for(let i=0;i<files.length;i++){
                        let file=files[i];
                        let filename=file.name;
                        //文件类型
                        let type = filename.substring(filename.lastIndexOf(".") );
                        if(!this.contains(type,accept)){
                            showErrorMessage('请选择:'+accept.join(",")+"格式的文件!");
                            return;
                        }
                    }
                    let formData = new FormData()
                    //添加多个文件到multipartFiles
                    for (const file of files) {
                        // 通过append向form对象添加多个文件，file不会被后一个替换
                        formData.append('files', file)
                    }
                    this.props.onChange(formData);

                    document.getElementById(buttonId).value="";

                }} />

            </div>
        );
    }
}

FormDataFileUploadButton.defaultProps={
    config:{accept: []},
    onChange:(fileContentArray)=>{}
};